from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import requests

from enterprise.models import Job
from map_app.models import AddressLocation


# 1. 提供前端所需的 Web 端 Key（避免前端硬编码）
class AmapWebKeyView(APIView):
    def get(self, request):
        return Response({
            "amap_web_key": settings.AMAP_API_KEY
        })


# 2. 地理编码接口转发（地址 → 经纬度）
class GeocodeView(APIView):
    def get(self, request):
        address = request.query_params.get("address", "").strip()
        city = request.query_params.get("city", "")  # 可选：指定城市，提高精度

        if not address:
            return Response(
                {"error": "地址不能为空"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 调用高德 Web 服务 API（地理编码）
        amap_url = "https://restapi.amap.com/v3/geocode/geo"
        params = {
            "address": address,
            "city": city,
            "key": settings.AMAP_SERVICE_KEY,
            "output": "json"
        }

        try:
            # 转发请求到高德 API
            response = requests.get(amap_url, params=params, timeout=5)
            response.raise_for_status()  # 抛出 HTTP 错误（如 404、500）
            return Response(response.json())  # 直接返回高德结果给前端
        except Exception as e:
            return Response(
                {"error": f"地理编码失败：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


# 3. POI 搜索接口转发（周边搜索、关键词搜索）
class PoiSearchView(APIView):
    def get(self, request):
        keywords = request.query_params.get("keywords", "").strip()  # 搜索关键词（如“餐厅”）
        location = request.query_params.get("location", "")  # 中心点经纬度（如“116.48,39.92”）
        radius = request.query_params.get("radius", 1000)  # 搜索半径（默认 1000 米）

        if not keywords or not location:
            return Response(
                {"error": "关键词和中心点经纬度不能为空"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 调用高德 POI 搜索 API
        amap_url = "https://restapi.amap.com/v3/place/text"
        params = {
            "keywords": keywords,
            "location": location,
            "radius": radius,
            "key": settings.AMAP_SERVICE_KEY,
            "output": "json",
            "page_size": 20  # 每页结果数
        }

        try:
            response = requests.get(amap_url, params=params, timeout=5)
            response.raise_for_status()
            return Response(response.json())
        except Exception as e:
            return Response(
                {"error": f"POI 搜索失败：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


# 新增接口：存储地址经纬度（map_api/views.py）
class SaveLocationView(APIView):
    def post(self, request):
        address = request.data.get("address", "").strip()
        longitude = request.data.get("longitude")
        latitude = request.data.get("latitude")

        if not address or not longitude or not latitude:
            return Response({"error": "参数不全"}, status=400)

        # 存储到数据库
        AddressLocation.objects.create(
            address=address,
            longitude=longitude,
            latitude=latitude
        )
        return Response({"message": "存储成功"}, status=201)


# 获取所有职位的经纬度
class JobLocationView(APIView):
    def get(self, request):
        # 查询所有职位，只返回核心字段（减少数据传输）
        jobs = Job.objects.all().values(
            "id", "title", "company", "salary_range", "work_city", "longitude", "latitude"
        )
        # 转换为列表（Django QuerySet 需序列化）
        job_list = list(jobs)
        # 格式化经纬度为字符串（适配前端高德地图）
        for job in job_list:
            job["longitude"] = str(job["longitude"])  # 格式化经度
            job["latitude"] = str(job["latitude"])
        return Response({
            "status": "success",
            "data": job_list
        })
